package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author dingchunlin
 * @Date 2023/12/2 14:29
 * @Version 1.0.0
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GuliMallExceptionControllerAdvice {

    /**
     * 参数校验处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题：{},异常类型为：{}", e.getMessage(), e.getClass());
        Map<String, String> map = new HashMap<String, String>();
        BindingResult result = e.getBindingResult();
            result.getFieldErrors().forEach((item) -> {
                //获取错误提示
                String message = item.getDefaultMessage();
                //获取哪个字段发生了错误
                String field = item.getField();
                map.put(field, message);
            });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 统一异常处理
     * @param e
     * @return
     */
//    @ExceptionHandler(value = Exception.class)
//    public R handleException(Exception e) {
//        log.error("报错：{},异常类型为：{}", e.getMessage(), e.getClass());
//        return R.error(BizCodeEnum.UNKNOW_EXEPTION.getCode(),BizCodeEnum.UNKNOW_EXEPTION.getMsg());
//    }
}
